package com.thinkfit.jy.utils;

import android.content.Context;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.common.lib.constant.EventBusEvent;
import com.jaygoo.widget.OnRangeChangedListener;
import com.jaygoo.widget.RangeSeekBar;
import com.thinkfit.jy.R;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

/**
 * CPU使用情况显示（用于在第三方应用中返回本应用）
 */
public class VolumeAndBrightnessViewUtils implements View.OnClickListener {

    private static VolumeAndBrightnessViewUtils volumeAndBrightnessViewUtils;
    WindowManager windowManager;
    Context mContext;
    boolean isFist = true;
    boolean isTounch = false;
    private AudioManager mAudioManager;
    View inflate;
    WindowManager.LayoutParams layoutParams;

    ConstraintLayout clItem,clBg;
    RangeSeekBar rsbBrigthness,rsbSound;

    TextView tvBrigthnessNum,tvSoundNum;
    ImageView ivClose;
    int mBrigthnessProgress,mSoundProgress,brigthnessProgress,volumeProgress;
    boolean isFirstBrigthness = true;
    boolean isFirstSound = true;
    float x,y;
    public static VolumeAndBrightnessViewUtils getInstance(){
        if(volumeAndBrightnessViewUtils == null){
            volumeAndBrightnessViewUtils = new VolumeAndBrightnessViewUtils();
        }
        return volumeAndBrightnessViewUtils;
    }


    public void initView(Context context){
        mContext = context;
        if(windowManager == null){
            windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }
        if(inflate == null){
            inflate = LayoutInflater.from(context).inflate(R.layout.item_volume_and_brightness, null);
//            DisplayMetrics dm = new DisplayMetrics();
//            windowManager.getDefaultDisplay().getMetrics(dm);
//            width = dm.widthPixels;         // 屏幕宽度（像素）
//            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   width : "+width);
//            float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
//            screenWidth = (int) (width / density);  // 屏幕宽度(dp)
            rsbBrigthness = inflate.findViewById(R.id.rsb_brigthness);
            tvBrigthnessNum = inflate.findViewById(R.id.tv_brigthness_num);
            rsbSound = inflate.findViewById(R.id.rsb_sound);
            tvSoundNum = inflate.findViewById(R.id.tv_sound_num);
            ivClose = inflate.findViewById(R.id.iv_close);

//            clItem = inflate.findViewById(R.id.cl_item);
            clBg = inflate.findViewById(R.id.cl_bg);
            ivClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    goneButton();
                }
            });
            clBg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    goneButton();
                }
            });

        }

        int currentBrigthness = SystemUtils.getBrightness(mContext);
        //最大亮度
        int mMaxBrigthness = SystemUtils.getMaxBrightness(mContext);
        brigthnessProgress = (int)((currentBrigthness/(mMaxBrigthness*1f))*100f);
        HashMap<Object, Object> map = new HashMap<>();
        rsbBrigthness.setRange(0,100);
        rsbBrigthness.setProgress(brigthnessProgress);
        tvBrigthnessNum.setText(brigthnessProgress+"%");
        rsbBrigthness.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                if(isFirstBrigthness){
                    isFirstBrigthness = false;
                    return;
                }

                mBrigthnessProgress = (int) (leftValue + 0.0001);
                tvBrigthnessNum.setText(mBrigthnessProgress+"%");
                int brigthnessVolume = (int)((mMaxBrigthness/100f)*mBrigthnessProgress);

                map.clear();
                map.put(EventBusEvent.BRIGHTNES_CHANGE, brigthnessVolume);
                EventBus.getDefault().post(map);
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }
        });

        int currentVolume = getAudioManager().getStreamVolume(AudioManager.STREAM_MUSIC);
        //媒体音量 STREAM_MUSIC    STREAM_RING 铃声音量
        int mMaxVolume = getAudioManager().getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        volumeProgress = (int)((currentVolume/(mMaxVolume*1f))*100f);
        rsbSound.setRange(0,100);
        rsbSound.setProgress(volumeProgress);
        tvSoundNum.setText(volumeProgress +"%");
        rsbSound.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                if(isFirstSound){
                    isFirstSound = false;
                    return;
                }
                mSoundProgress = (int) (leftValue + 0.0001);
                tvSoundNum.setText(mSoundProgress+"%");

                int volume = (int) ((mMaxVolume/100f)*mSoundProgress);

                map.clear();
                map.put(EventBusEvent.VOICE_CHANGE, volume);
                EventBus.getDefault().post(map);
                if(volume <= 0){
                    getAudioManager().setRingerMode(AudioManager.RINGER_MODE_SILENT);
                }else {
                    getAudioManager().setRingerMode(AudioManager.RINGER_MODE_NORMAL);

                }
                //设置铃声音量
                getAudioManager().setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
                SportsStatusBarViewUtils.getInstance().setVolume(volume);

            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }
        });


        if(layoutParams == null){
            layoutParams = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    PixelFormat.TRANSLUCENT
            );

            layoutParams.gravity = Gravity.CENTER;
        }


        if(isFist){
            isFist = false;
            windowManager.addView(inflate,layoutParams);
        }else {
            inflate.setVisibility(View.VISIBLE);
        }

    }

    private AudioManager getAudioManager() {
        if (mAudioManager == null) {
            mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        }
        return mAudioManager;
    }


    public void goneButton(){
        if(windowManager != null){
            if(inflate != null){
                inflate.setVisibility(View.GONE);
            }
        }

    }

    @Override
    public void onClick(View v) {

    }


    /**
     * dp2px
     */
    protected int dp2px(float dpValue) {
        float density = mContext.getResources().getDisplayMetrics().density;
        return (int) (dpValue * density + 0.5f);
    }


}
